package com.supply.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 将文件上传到阿里云Oss存储中心的工具类
 */
public class OssUtils {
    private static String bucketName = "lyj-mall-bucket";

    private static String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";

    private static String accessKey = "LTAI5tC9jHg4CwcEgfssGSFG";

    private static String secretKey = "tFuaXUNNFUtvsElcd8WBnCrHuf7qSD";

    private static String bucketEndpoint = "https://lyj-mall-bucket.oss-cn-guangzhou.aliyuncs.com";

    public static String upload(String filename, InputStream inputStream){
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKey,secretKey);

        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("你已创建Bucket :" + bucketName);
        } else {
            System.out.println("bucket不存在，创建Bucket: " + bucketName);
            ossClient.createBucket(bucketName);
        }

        //设计一个存储对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        System.out.println("文件名称：" + filename);
        String objectName = sdf.format(new Date()) + "/" + filename;

        //存储对象
        ossClient.putObject(bucketName,objectName,inputStream);
        String httpURL = bucketEndpoint +"/" + objectName;

        ossClient.shutdown();
        return  httpURL;
    }
}
